﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Supplier_Location_Vehicles : System.Web.UI.Page
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    private int SupplierId
    {
        get
        {
            if (UserAccess.IsCurrentUser(Enums.UserTypes.Admin))
                return Helper.QSIntValue("sid");
            else
                return UserAccess.CurrentSupplier.SupplierId;
        }
    }
    private int SupplierLocationId
    {
        get { return Helper.QSIntValue("slid"); }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((BaseMasterPage)this.Master).CurrentPage = PageConfig.Pages.SupplierLocationDefault;
        if (!((BaseMasterPage)this.Master).AuthorizeCurrentUser())
            return;
        ltrMessage.Text = string.Empty;
        if (!IsPostBack)
        {
            if (SupplierLocationId == 0 || SupplierId == 0)
            {
                Response.Redirect("default.aspx", true);
            }
            else
            {
                LoadVehicles(ddlSupplierVehicleAdd, "0");
                LoadSupplierVehicles();
                ltrLocation.Text = supplierContext.Locations.FirstOrDefault(l => l.LocationId == supplierContext.SupplierLocations.FirstOrDefault(P => P.SupplierLocationId == SupplierLocationId).LocationId).LocationName;
                ltrSupplier.Text = supplierContext.Suppliers.FirstOrDefault(s => s.SupplierId == SupplierId).SupplierName;

            }

        }
    }

    private void LoadSupplierVehicles()
    {
        gvVehicles.DataSource = from slv in supplierContext.SupplierLocationVehicles
                                where slv.SupplierLocationId == SupplierLocationId
                                select slv;

        gvVehicles.DataBind();
    }

    protected void gvVehicles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int id = Convert.ToInt32(gvVehicles.DataKeys[e.Row.RowIndex].Value);
            SupplierLocationVehicle slv = (SupplierLocationVehicle)e.Row.DataItem;

            if((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList ddlSupplierVehicleEdit = (DropDownList)e.Row.FindControl("ddlSupplierVehicleEdit");
                CheckBox chkOnRequestEdit = (CheckBox)e.Row.FindControl("chkOnRequestEdit");
                TextBox txtInsurancePriceEdit = (TextBox)e.Row.FindControl("txtInsurancePriceEdit");
                TextBox txtInsuranceSellPriceEdit = (TextBox)e.Row.FindControl("txtInsuranceSellPriceEdit");

                if (slv != null)
                {
                    LoadVehicles(ddlSupplierVehicleEdit, slv.SupplierVehicleId.Value.ToString());
                    chkOnRequestEdit.Checked = slv.OnRequest.Value;
                    txtInsurancePriceEdit.Text = slv.InsurancePrice.Value.ToString();
                    txtInsuranceSellPriceEdit.Text = slv.InsuranceSellPrice.Value.ToString();
                }
            }
            else if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                Label lblVehicleName = (Label)e.Row.FindControl("lblVehicleName");
                Label lblOnRequest = (Label)e.Row.FindControl("lblOnRequest");
                Label lblInsurancePrice = (Label)e.Row.FindControl("lblInsurancePrice");
                Label lblInsuranceSellPrice = (Label)e.Row.FindControl("lblInsuranceSellPrice");
                if (slv != null)
                {
                    SupplierVehicle sv = supplierContext.SupplierVehicles.FirstOrDefault(p => p.SupplierVehicleId == slv.SupplierVehicleId);
                    lblVehicleName.Text = sv.VehicleCode + "-" + sv.VehicleDescription;
                    lblOnRequest.Text = slv.OnRequest.Value ? "Yes" : "No";
                    lblInsurancePrice.Text = slv.InsurancePrice.Value.ToString(Constants.DECIMAL_FORMAT);
                    lblInsuranceSellPrice.Text = slv.InsuranceSellPrice.Value.ToString(Constants.DECIMAL_FORMAT);
                }

                ((LinkButton)e.Row.Cells[5].Controls[0]).OnClientClick = "return confirm(\"Are you sure you want to delete this vehicle from the list?\");";
            }
        }
        //else if (e.Row.RowType == DataControlRowType.Footer)
        //{
        //    DropDownList ddlSupplierVehicleAdd = (DropDownList)e.Row.FindControl("ddlSupplierVehicleAdd");
        //    LoadVehicles(ddlSupplierVehicleAdd, "0");
        //}
    }

    private void LoadVehicles(DropDownList ddl, string selectedValue)
    {
        //E.G. - NEASTED QUERY OF LINQ SAMPLE... DONT REMOVE
        //ddl.DataSource = from sv in supplierContext.SupplierVehicles
        //                 where sv.SupplierId == SupplierId
        //                 && !(from slv in supplierContext.SupplierLocationVehicles
        //                      where slv.SupplierLocationId == SupplierLocationId
        //                      select slv).Any(p => p.SupplierVehicleId == sv.SupplierVehicleId)
        //                 select new { Text = sv.VehicleCode + "-" + sv.VehicleDescription, Value = sv.SupplierVehicleId };

        ddl.DataSource = from sv in supplierContext.SupplierVehicles
                         where sv.SupplierId == SupplierId
                         select new { Text = sv.VehicleCode + "-" + sv.VehicleDescription, Value = sv.SupplierVehicleId };
        ddl.DataTextField = "Text";
        ddl.DataValueField = "Value";
        ddl.DataBind();

        ddl.Items.Insert(0, new ListItem("Select Vehicle", "0"));

        if (!string.IsNullOrEmpty(selectedValue))
            ddl.SelectedValue = selectedValue;
    }
    protected void gvVehicles_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //if (e.CommandName == "ADD")
        //{
        //    GridViewRow row = gvVehicles.FooterRow;

        //    DropDownList ddlSupplierVehicleAdd = (DropDownList)row.FindControl("ddlSupplierVehicleAdd");
        //    CheckBox chkOnRequestAdd = (CheckBox)row.FindControl("chkOnRequestAdd");
        //    TextBox txtInsurancePriceAdd = (TextBox)row.FindControl("txtInsurancePriceAdd");
        //    TextBox txtInsuranceSellPriceAdd = (TextBox)row.FindControl("txtInsuranceSellPriceAdd");
        //    if (!AlreadyInserted(Convert.ToInt32(ddlSupplierVehicleAdd.SelectedValue), 0))
        //    {
        //        SupplierLocationVehicle slv = new SupplierLocationVehicle
        //        {
        //            SupplierId = this.SupplierId,
        //            SupplierVehicleId = Convert.ToInt32(ddlSupplierVehicleAdd.SelectedValue),
        //            OnRequest = chkOnRequestAdd.Checked,
        //            InsurancePrice = Convert.ToDecimal(txtInsurancePriceAdd.Text),
        //            InsuranceSellPrice = Convert.ToDecimal(txtInsuranceSellPriceAdd.Text),
        //            SupplierLocationId = SupplierLocationId,
        //            LocationId = supplierContext.SupplierLocations.FirstOrDefault(p => p.SupplierLocationId == SupplierLocationId).LocationId
        //        };

        //        supplierContext.SupplierLocationVehicles.InsertOnSubmit(slv);
        //        supplierContext.SubmitChanges();

        //        Response.Redirect("vehicles.aspx?&slid=" + this.SupplierLocationId.ToString() + "&sid=" + SupplierId.ToString());
        //    }
        //    else
        //    {
        //        ltrMessage.Text = "Vehicle is already inserted for this location";
        //    }
        //}
    }
    protected void gvVehicles_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void gvVehicles_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(gvVehicles.DataKeys[e.RowIndex].Value);
        SupplierLocationVehicle slv = supplierContext.SupplierLocationVehicles.FirstOrDefault(p => p.SupplierLocationVehicleId == id);
        supplierContext.SupplierLocationVehicles.DeleteOnSubmit(slv);
        supplierContext.SubmitChanges();

        Response.Redirect("vehicles.aspx?&slid=" + this.SupplierLocationId.ToString() + "&sid=" + SupplierId.ToString());
    }
    protected void gvVehicles_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

    }
    protected void gvVehicles_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gvVehicles.Rows[Convert.ToInt32(e.RowIndex)];
        DropDownList ddlSupplierVehicleEdit = (DropDownList)row.FindControl("ddlSupplierVehicleEdit");
        CheckBox chkOnRequestEdit = (CheckBox)row.FindControl("chkOnRequestEdit");
        TextBox txtInsurancePriceEdit = (TextBox)row.FindControl("txtInsurancePriceEdit");
        TextBox txtInsuranceSellPriceEdit = (TextBox)row.FindControl("txtInsuranceSellPriceEdit");

        int id = Convert.ToInt32(gvVehicles.DataKeys[e.RowIndex].Value);
        if (!AlreadyInserted(Convert.ToInt32(ddlSupplierVehicleEdit.SelectedValue), id))
        {
            SupplierLocationVehicle slv = supplierContext.SupplierLocationVehicles.FirstOrDefault(p => p.SupplierLocationVehicleId == id);

            slv.SupplierId = this.SupplierId;
            slv.SupplierVehicleId = Convert.ToInt32(ddlSupplierVehicleEdit.SelectedValue);
            slv.OnRequest = chkOnRequestEdit.Checked;
            slv.InsurancePrice = Convert.ToDecimal(txtInsurancePriceEdit.Text);
            slv.InsuranceSellPrice = Convert.ToDecimal(txtInsuranceSellPriceEdit.Text);
            slv.SupplierLocationId = SupplierLocationId;
            slv.LocationId = supplierContext.SupplierLocations.FirstOrDefault(p => p.SupplierLocationId == SupplierLocationId).LocationId;

            supplierContext.SubmitChanges();

            Response.Redirect("vehicles.aspx?&slid=" + this.SupplierLocationId.ToString() + "&sid=" + SupplierId.ToString());
        }
        else
        {
            ltrMessage.Text = "Vehicle is already inserted for this location";
        }

    }
    protected void gvVehicles_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvVehicles.EditIndex = e.NewEditIndex;
        LoadSupplierVehicles();
    }
    protected void gvVehicles_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvVehicles.EditIndex = -1;
        LoadSupplierVehicles();
    }

    private bool AlreadyInserted(int vehicleId, int suppLocVihId)
    {

        var v = supplierContext.SupplierLocationVehicles.FirstOrDefault(slv => slv.SupplierLocationVehicleId != suppLocVihId && slv.SupplierVehicleId == vehicleId && slv.SupplierLocationId == SupplierLocationId);

        return (v != null);
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (!AlreadyInserted(Convert.ToInt32(ddlSupplierVehicleAdd.SelectedValue), 0))
        {
            SupplierLocationVehicle slv = new SupplierLocationVehicle
            {
                SupplierId = this.SupplierId,
                SupplierVehicleId = Convert.ToInt32(ddlSupplierVehicleAdd.SelectedValue),
                OnRequest = chkOnRequestAdd.Checked,
                InsurancePrice = Convert.ToDecimal(txtInsurancePriceAdd.Text),
                InsuranceSellPrice = Convert.ToDecimal(txtInsuranceSellPriceAdd.Text),
                SupplierLocationId = SupplierLocationId,
                LocationId = supplierContext.SupplierLocations.FirstOrDefault(p => p.SupplierLocationId == SupplierLocationId).LocationId
            };

            supplierContext.SupplierLocationVehicles.InsertOnSubmit(slv);
            supplierContext.SubmitChanges();

            Response.Redirect("vehicles.aspx?&slid=" + this.SupplierLocationId.ToString() + "&sid=" + SupplierId.ToString());
        }
        else
        {
            ltrMessage.Text = "Vehicle is already inserted for this location";
        }
    }
}
